
package vv.lines.core;

import vv.lines.core.context.IContext;
import vv.lines.view.FieldItemView;
import vv.lines.view.View;

/**
 *
 * @author vpotapenko
 */
public abstract class AbstractFieldItem extends VisualObject implements IActionHandler {

    private Field field;

    private int x, y;
    private int width, height;
    private boolean visible;
    private int zOrder;

    AbstractFieldItem(IContext context) {
        super(context);
    }

    public void setZOrder(int zOrder) {
        if (zOrder == this.zOrder) return;

        this.zOrder = zOrder;

        FieldItemView view = getView();
        view.setZOrder(zOrder);

        fireChangeZOrder();
    }

    @Override
    public void setView(View view) {
        super.setView(view);

        syncView();
    }

    protected void syncView() {
        syncViewBounds();
        setVisible(visible);
    }

    @Override
    public FieldItemView getView() {
        return (FieldItemView) super.getView();
    }

    public Field getField() {
        return field;
    }

    public void setField(Field field) {
        removeViewFromField();

        this.field = field;

        addViewToField();
    }

    protected void syncViewBounds() {
        FieldItemView view = getView();
        if (view == null) return;

        view.setLocation(x, y);
        view.setSize(width, height);
    }

    public void setSize(int width, int height) {
        this.width = width;
        this.height = height;

        syncViewBounds();
    }

    public int getWidth() {
        return width;
    }

    public int getHeight() {
        return height;
    }

    public void setLocation(int x, int y) {
        this.x = x;
        this.y = y;

        syncViewBounds();
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public void setVisible(boolean visible) {
        this.visible = visible;

        FieldItemView view = getView();
        if (view != null) view.setVisible(visible);
    }

    private void addViewToField() {
        if (field != null) field.getView().add(getView());
    }

    private void fireChangeZOrder() {
        if (field != null) field.getView().updateItemsZOrder();
    }

    private void removeViewFromField() {
        if (field != null) field.getView().remove(getView());
    }
}
